package cn.geminis.auth.server.service;

import cn.geminis.resources.core.client.UserClient;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author puddi
 */
@Service
@AllArgsConstructor
public class GeminiAuthenticationProvider implements AuthenticationProvider {

    private final UserClient userClient;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        var usernamePasswordAuthentication = (UsernamePasswordAuthenticationToken) authentication;
        var username = usernamePasswordAuthentication.getName();
        var password = usernamePasswordAuthentication.getCredentials().toString();

        var checkResult = this.userClient.checkPassword(username, password);
        if (!checkResult) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
    }

    @Override
    public boolean supports(Class<?> authenticate) {
        return authenticate.equals(UsernamePasswordAuthenticationToken.class);
    }
}
